//
//  XLBarCharView.swift
//  XLProject
//
//  Created by xinglian on 2022/4/25.
//

import UIKit
import Charts
import TCCKit
@objc protocol XLCharViewDelegate
{
    /// 图表中，数值被选中
    @objc func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight)
    ///图表中，空白区域被选中
    @objc optional func chartValueNothingSelected(_ chartView: ChartViewBase)
    /// 图形每个entriys 的颜色
    @objc optional func chartDataSet(_ datas:[ChartDataEntryBase])->ChartData
    
    @objc optional func stringForValue(_ value: Double, axis: AxisBase?) -> String
}

///柱状图
@objcMembers class XLBarCharView: UIView {
    /// 有效值，低于此值不显示
    var validValue = 0
    private var charData = BarChartData()
    var delegate:XLCharViewDelegate?=nil
    var lastValidEntry : ChartDataEntry?=nil
    var showLastEntry = true
    var setColor = "#1D78FF"
    var xVals=[String]()
    /// 数值数组
    var objcarray = NSArray(){
        didSet{
            var arr = [Any]()
            for ojb in objcarray {
                arr.append(Double("\(ojb)"))
            }
            self.array = arr
        }
    }
    var array = [Any](){
        didSet{
            var showArray = [BarChartDataEntry]()
            self.lastValidEntry = nil
            for i in 0..<array.count
            {
                let y : Double = array[i] as? Double ?? Double("\(array[i])")!
                let entry = BarChartDataEntry(x:Double(i), y:y)
                showArray.append(entry)
                if y > Double(self.validValue){
                    self.lastValidEntry = entry
                }
            }
            self.setupBar(showArray)
            ///默认最后一次有效选中状态
            if self.lastValidEntry != nil && self.showLastEntry{
                self.delegate?.chartValueSelected(self.charView, entry: self.lastValidEntry!, highlight: Highlight())
            }
        }
    }
    
    private func setupBar(_ array:[BarChartDataEntry])
    {
        self.charView.data = nil
        for dataset in self.charData.dataSets{
            self.charData.removeDataSet(dataset)
        }
        
        let charData = self.delegate?.chartDataSet?(array)
        if charData != nil{
            self.charData = charData as! BarChartData
            self.charView.data = self.charData
            return
        }
        
        let set = BarChartDataSet(entries:array, label:"")
        set.setColor(self.setColor.color())
        set.drawValuesEnabled = false
        set.axisDependency = .right//这个属性重要，以右边y轴为准
        self.charData = BarChartData(dataSet:set)
        self.charView.data = self.charData
        //        self.charView.animate(yAxisDuration:1.0)
    }
    
    lazy var charView : BarChartView = {
        let char = BarChartView()
        char.frame = self.bounds
        self.addSubview(char)
 
        ///基本样式
        char.delegate = self
        
        //设置间隙
        char.setExtraOffsets(left:10, top:0, right:0, bottom:20)
        char.noDataText = ""
        //x,y轴是否支持拖拽
        char.scaleXEnabled = false
        char.scaleXEnabled = false
        //x,y轴是否支持同时缩放
        char.pinchZoomEnabled = false
        //是否支持双击缩放
        char.doubleTapToZoomEnabled = false
        //图表的描述
        char.chartDescription?.enabled = true
        //是否显示图例
        char.legend.enabled = false
        char.drawValueAboveBarEnabled = true//数值显示在柱形的上面还是下面
        char.fitBars = true //统计图完全显示
        
        
        let leftAxis = char.leftAxis
        leftAxis.enabled = false
        leftAxis.drawGridLinesEnabled = false
        leftAxis.gridLineDashLengths = [2,2]
        leftAxis.axisLineWidth = 0
        leftAxis.labelTextColor = "#666666".color()
        leftAxis.labelPosition = .outsideChart
        leftAxis.drawLabelsEnabled = true
        leftAxis.axisMinimum = 0//Y轴最小值（不然不会从0开始）
        //        leftAxis.drawZeroLineEnabled = true
        leftAxis.forceLabelsEnabled = true //强制绘制制定数量的label
        leftAxis.labelCount = 6
        
        let rightAxis = char.rightAxis
        rightAxis.enabled = false
        rightAxis.drawLabelsEnabled = true
        rightAxis.gridLineDashLengths = [2,2]
        rightAxis.labelPosition = .outsideChart
        rightAxis.axisLineColor = .clear// Y轴颜色，透明可以隐藏右边y轴
        rightAxis.labelCount = 6
        rightAxis.labelFont = UIFont.systemFont(ofSize: 11)
        rightAxis.labelTextColor = "#666666".color()
        rightAxis.forceLabelsEnabled = true
        rightAxis.axisMinimum = 0//Y轴最小值（不然不会从0开始）
//        rightAxis.valueFormatter = self
        //        rightAxis.drawZeroLineEnabled = true
        
        let xAxis = char.xAxis
        xAxis.enabled = true
        xAxis.axisLineColor = "#EDEDED".color()
        xAxis.labelPosition = .bottom
        //不绘制网线
        xAxis.drawGridLinesEnabled = false
        //xAxis.labelFont = font(11)//x轴数值字体大小
        xAxis.labelTextColor = "#666666".color()//数值字体颜色
//        xAxis.granularity = 1 
        //避免文字显示不全 这个属性很重要,设置会影响x轴标签的左右位置
        xAxis.avoidFirstLastClippingEnabled = true
//        xAxis.forceLabelsEnabled = true
        xAxis.valueFormatter = self
        return char
    }()
}
//MARK: - ChartViewDelegate
extension XLBarCharView:ChartViewDelegate
{
    ///图表中，数值被选中
    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        self.delegate?.chartValueSelected(chartView, entry: entry, highlight: highlight)
    }
    
    ///图表中，空白区域被选中
    func chartValueNothingSelected(_ chartView: ChartViewBase) {
        self.delegate?.chartValueNothingSelected?(chartView)
    }
    
    ///图表中，被缩放
    func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
        
    }
    
    ///图表中，图表被移动
    func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) {
        
    }
}
//MARK: - IAxisValueFormatter
extension XLBarCharView:IAxisValueFormatter{
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        let str = self.delegate?.stringForValue?(value, axis: axis)
        if str != nil{
            return str!
        }
        
        if axis!.isKind(of: XAxis.self){
            let i = Int(value - axis!.axisMinimum)
            if i < self.xVals.count && i >= 0{
                return self.xVals[i]
            }
            return ""
        }
       
        return ""
    }
}
